package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.reggie.common.R;
import com.reggie.entity.User;
import com.reggie.service.UserService;
import com.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;



    @PostMapping("/sendMsg")
    public R<String>  sendMsg(@RequestBody User user, HttpSession session){
        String email=user.getPhone();
        String subject="瑞吉外卖";

        if (StringUtils.isNotBlank(email)){
            String code= ValidateCodeUtils.generateValidateCode(4).toString();
            String text="【瑞吉外卖】您好，您的登录验证码为：" + code + "，请尽快登录";
            log.info("code={}",code);
//            把验证码存入session
//            session.setAttribute(email,code);
//            验证码存入redis中
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
              valueOperations.set(email,code,5, TimeUnit.MINUTES);
            try {
              userService.sendMsg(email,subject,text);
                return R.success("邮箱验证码发送成功");
            }catch (MailException e){
                e.printStackTrace();
            }

        }
        return R.error("邮箱验证码发送失败");
    }

    //    移动应用登录端
    @PostMapping("/login")
//    这里使用map来接收前端传过来的值
    private R<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());
        String email=map.get("phone").toString();
        String code=map.get("code").toString();
//     取出存入的验证码
//        Object codeInSession = session.getAttribute(email);

//        取出存入redis中的验证码
        String codeInSession = redisTemplate.opsForValue().get(email);
//        进行验证码比对(页面提交的验证码 和session中 的验证码比对)
        if (codeInSession!=null && codeInSession.equals(code)){
         LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
         queryWrapper.eq(User::getPhone,email);
//         查询数据库是否有这个用户
            User user = userService.getOne(queryWrapper);
//            没有就创建
            if (user==null){
                user=new User();
                user.setPhone(email);
                user.setStatus(1);
                user.setName(email.substring(0,6));
                userService.save(user);
            }
//            过滤器需要这个userId放行
            session.setAttribute("user",user.getId());

//            如果登录成功,删除redis中缓存的验证码
            redisTemplate.delete(email);
            return R.success(user);
        }

        return R.error("登录失败");
    }

//    退出登录
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }


}
